package skills.jssvc.deu.cn.skillsecond.programming1;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

import skills.jssvc.deu.cn.skillsecond.MyApplication;
import skills.jssvc.deu.cn.skillsecond.R;
import skills.jssvc.deu.cn.skillsecond.bean.Balance;
import skills.jssvc.deu.cn.skillsecond.util.HttpRequest;
import skills.jssvc.deu.cn.skillsecond.util.SqlHelper;


public class MyAccount_Fragment_1 extends Fragment {
   private final String TAG = "Fragment1";
   private View view;
   private TextView balanceTv;
   private Spinner spinner;
   private EditText amountET;
   private Button queryBtn,okBtn;
   private ArrayAdapter<String> spinnerAdapter;
   private int carId=1;
   private SqlHelper helper;
   private SQLiteDatabase db;

   @Nullable
   @Override
   public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
      view = inflater.inflate(R.layout.fragment1_myaccount1, container, false);
      initView();
      setListen();
//      query(carId);
      return view;
   }

   private void initView(){
      balanceTv = (TextView) view.findViewById(R.id.frag1_balance_tv);
      spinner = (Spinner) view.findViewById(R.id.frag1_car_spinner);
      amountET = (EditText) view.findViewById(R.id.frag1_amount_et);
      queryBtn = (Button) view.findViewById(R.id.frag1_query_btn);
      okBtn = (Button) view.findViewById(R.id.frag1_ok_btn);
      final String[] items = new String[]{"1", "2", "3", "4"};
      spinnerAdapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_spinner_item,items);
      spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      spinner.setAdapter(spinnerAdapter);
   }

   private void setListen(){
      okBtn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
            if(!amountET.getText().toString().equals("")){
               int money = Integer.valueOf(amountET.getText().toString().trim());
               if(money>0 &&money<999){
                  top(carId,money);
               }else {
                  Toast.makeText(MyApplication.appContext, "请输入0~999之间的金额！", Toast.LENGTH_SHORT).show();
               }
            }else {
               Toast.makeText(MyApplication.appContext, "请输入充值金额！", Toast.LENGTH_SHORT).show();
            }
         }
      });

      queryBtn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
            query(carId);
         }
      });

      spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
         @Override
         public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            carId = i+1;
         }

         @Override
         public void onNothingSelected(AdapterView<?> adapterView) {
         }
      });
   }

   private void query(int carid){
      String url = "GetCarAccountBalance";
//      String parma = "{\"CarId\":2, \"UserName\":\"user1\"}";
      String parma = "{\"CarId\":"+String.valueOf(carid)+", \"UserName\":\"user1\"}";
      HttpRequest.post(url, parma, new Response.Listener<JSONObject>() {
         @Override
         public void onResponse(JSONObject jsonObject) {
            Balance balance = new Gson().fromJson(jsonObject.toString(), Balance.class);
            balanceTv.setText(String.valueOf(balance.getBalance()));
            queryRecord();
         }
      }, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError volleyError) {
            Toast.makeText(MyApplication.appContext, "查询错误！", Toast.LENGTH_SHORT).show();
         }
      });
   }

   private void top(final int carId, final int amount){
      String param = "{\"CarId\":"+String.valueOf(carId)+",\"Money\":"+String.valueOf(amount)+", \"UserName\":\"user1\"}";
      HttpRequest.post("SetCarAccountRecharge", param, new Response.Listener<JSONObject>() {
         @Override
         public void onResponse(JSONObject jsonObject) {
            try {
               if(jsonObject.getString("RESULT").equals("S")){
                  Toast.makeText(MyApplication.appContext, "充值成功！", Toast.LENGTH_SHORT).show();
                  query(carId);
                  record(carId,amount,"user");
               }
            } catch (JSONException e) {
               e.printStackTrace();
            }
         }
      }, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError volleyError) {
            Toast.makeText(MyApplication.appContext, "充值错误！", Toast.LENGTH_SHORT).show();
         }
      });
   }

   private void record(int carId,int amount,String user){
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      String time = format.format(new Date(System.currentTimeMillis()));
      helper = new SqlHelper(getContext(),SqlHelper.DA_NAME,null,1);
      db = helper.getWritableDatabase();
      ContentValues values = new ContentValues();
      values.put("carId",carId);
      values.put("amount",amount);
      values.put("time",time);
      values.put("user",user);
      db.insert(SqlHelper.table_top, null, values);
      values.clear();
      db.close();
   }

   private void queryRecord(){
      helper = new SqlHelper(MyApplication.appContext, SqlHelper.DA_NAME, null, 1);
      db = helper.getWritableDatabase();
      Cursor cursor = db.query(SqlHelper.table_top, null, null, null, null, null, null);
      if(cursor.moveToFirst()){
         do {
            Log.d(TAG, "queryRecord: cursor=" + cursor.getString(cursor.getColumnIndex("time")));
         } while (cursor.moveToNext());
      }
      cursor.close();
      db.close();
   }

}
